namespace Skymate.Mvc.Controllers.Filters
{
    using System.Net;
    using System.Net.Http;
    using System.Web.Http.Filters;

    using Castle.Core.Logging;

    using Skymate;
    using Skymate.Engines;
    using Skymate.Mvc.Models;

    /// <summary>
    /// Used to handle exceptions on web api controllers.
    /// </summary>
    public class AbpExceptionFilterAttribute : ExceptionFilterAttribute, ITransientDependency
    {
        public ILogger Logger { get; set; }
        
        public AbpExceptionFilterAttribute()
        {
            this.Logger = NullLogger.Instance;
            
        }

        /// <summary>
        /// Raises the exception event.
        /// </summary>
        /// <param name="context">The context for the action.</param>
        public override void OnException(HttpActionExecutedContext context)
        {
            LogHelper.LogException(this.Logger, context.Exception);

            context.Response = context.Request.CreateResponse(
                HttpStatusCode.OK,
                new AjaxResponse(
                    ErrorInfoBuilder.Instance.BuildForException(context.Exception),
                    context.Exception is Abp.Authorization.AbpAuthorizationException)
                );
            
        }
    }
}